{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46a6ad6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96d51078",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%html\n",
    "<style>\n",
    ".cell-output-ipywidget-background {\n",
    "    background-color: transparent !important;\n",
    "}\n",
    ":root {\n",
    "    --jp-widgets-color: var(--vscode-editor-foreground);\n",
    "    --jp-widgets-font-size: var(--vscode-editor-font-size);\n",
    "}  \n",
    "</style>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7dd70e04",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "\n",
    "splits = {\n",
    "    \"testmini\": \"data/testmini-00000-of-00001-725687bf7a18d64b.parquet\",\n",
    "    \"test\": \"data/test-*.parquet\",\n",
    "}\n",
    "df = pl.read_parquet(\"hf://datasets/AI4Math/MathVista/\" + splits[\"testmini\"]).sample(\n",
    "    fraction=1.0, shuffle=True, seed=42\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81e02b97",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Iterator, TypedDict, cast\n",
    "\n",
    "\n",
    "class DecodedImage(TypedDict):\n",
    "    bytes: bytes\n",
    "\n",
    "\n",
    "class Scenario(TypedDict):\n",
    "    pid: int\n",
    "    question: str\n",
    "    answer: str\n",
    "    image: str\n",
    "    decoded_image: DecodedImage\n",
    "\n",
    "\n",
    "val_scenarios = cast(list[Scenario], df.head(64).to_dicts())\n",
    "train_scenarios_iter = cast(Iterator[Scenario], df.tail(-64).iter_rows(named=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9287d8fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "import art\n",
    "from art.local import LocalBackend\n",
    "\n",
    "model = art.TrainableModel(\n",
    "    name=\"002\",\n",
    "    project=\"math-vista\",\n",
    "    base_model=\"Qwen/Qwen2.5-VL-7B-Instruct\",\n",
    ")\n",
    "backend = LocalBackend()\n",
    "await model.register(backend)\n",
    "client = model.openai_client()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c92b4b11",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def rollout(scenario: Scenario) -> art.Trajectory:\n",
    "    image_path = f\"/tmp/{scenario['image']}\"\n",
    "\n",
    "    import os\n",
    "\n",
    "    os.makedirs(os.path.dirname(image_path), exist_ok=True)\n",
    "\n",
    "    with open(image_path, \"wb\") as f:\n",
    "        f.write(scenario[\"decoded_image\"][\"bytes\"])\n",
    "\n",
    "    trajectory = art.Trajectory(messages_and_choices=[], reward=0.0)\n",
    "    trajectory.messages_and_choices = [\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": [\n",
    "                {\n",
    "                    \"type\": \"text\",\n",
    "                    \"text\": scenario[\"question\"]\n",
    "                    + \"\\n\\nNote: Provide your answer in a LaTeX box.\",\n",
    "                },\n",
    "                {\"type\": \"image_url\", \"image_url\": {\"url\": f\"file://{image_path}\"}},\n",
    "            ],\n",
    "        }\n",
    "    ]\n",
    "    chat_completion = await client.chat.completions.create(\n",
    "        model=model.name, messages=trajectory.messages()\n",
    "    )\n",
    "    choice = chat_completion.choices[0]\n",
    "    trajectory.messages_and_choices.append(choice)\n",
    "    content = choice.message.content\n",
    "    assert content is not None\n",
    "    if matches := list(re.finditer(r\"\\\\boxed\\{(.*?)\\}\", content, re.DOTALL)):\n",
    "        match = matches[-1]\n",
    "        answer = match.group(1)\n",
    "        if answer.lower() == scenario[\"answer\"].lower():\n",
    "            trajectory.reward = 1.0\n",
    "    return trajectory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "359e530d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import itertools\n",
    "\n",
    "SCENARIOS_PER_STEP = 8\n",
    "TRAJECTORY_GROUP_SIZE = 8\n",
    "start = await model.get_step()\n",
    "train_scenarios_iter = itertools.cycle(train_scenarios_iter)\n",
    "for _ in range(start * SCENARIOS_PER_STEP):\n",
    "    next(train_scenarios_iter)\n",
    "\n",
    "for i in range(start, 1000):\n",
    "    train_scenarios = [next(train_scenarios_iter) for _ in range(SCENARIOS_PER_STEP)]\n",
    "    val_trajectories, train_trajectory_groups = await asyncio.gather(\n",
    "        art.gather_trajectories(\n",
    "            (rollout(scenario) for scenario in val_scenarios),\n",
    "            pbar_desc=\"gather(val)\",\n",
    "            max_exceptions=32,\n",
    "        ),\n",
    "        art.gather_trajectory_groups(\n",
    "            (\n",
    "                art.TrajectoryGroup(\n",
    "                    rollout(scenario) for _ in range(TRAJECTORY_GROUP_SIZE)\n",
    "                )\n",
    "                for scenario in train_scenarios\n",
    "            ),\n",
    "            pbar_desc=\"gather(train)\",\n",
    "            max_exceptions=32,\n",
    "        ),\n",
    "    )\n",
    "    await model.log(val_trajectories)\n",
    "    await model.train(train_trajectory_groups)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
